import React from 'react';
import { connect } from 'dva';
import { Picker,Radio, List, NavBar,Icon, InputItem , TabBar,DatePicker ,Toast ,Button,TextareaItem,WhiteSpace,Flex,Checkbox,Modal  } from 'antd-mobile';
import { createForm } from 'rc-form';
import Reset from '../../style/ResetInput.less'
import { Link } from 'dva/router';
import style from '../../style/App.less'
import reqwest from 'reqwest';
import {numvail,selectvail} from '../../utils/Validator.js'
import options from '../../models/CityData.js'
import PropTypes from 'prop-types';
import {range,disabledDate,disabledDateTime } from '../../utils/Date.js'
import moment from 'moment';
import {reqwest_get,reqwest_post} from '../../utils/Reqwest.js';
import 'moment/locale/zh-cn';
const RadioItem = Radio.RadioItem;
const CheckboxItem = Checkbox.CheckboxItem;
const AgreeItem = Checkbox.AgreeItem;
const Alert = Modal.alert;
const maxTime = moment('22:00 +0800', 'HH:mm Z').utcOffset(8);
const minTime = moment('08:30 +0800', 'HH:mm Z').utcOffset(8);
class OrderEdit extends React.Component{
		constructor(props){
		super(props);
		this.state={
			reginos:[],
			disable:true,
      value:'saler_director',
      saler_boss:null,
      _regions:[],
      visible:false,
		}
	}
	// loadServer(params={}){
	// 	console.log(params)
	// 	const _this = this;
 //    // this.state.saler_boss!=null?
	// 	reqwest({
 //      url: window.host+'/api/orders',
 //      method: 'post',
 //      crossOrigin: true,
 //      type: 'json',
 //      data:{  access_token:localStorage['token'],
 //        id:_this.props.location.query.clue,
 //        order:{expected_square:params.square,booking_date:params.booking_date,cgj_company_id:params.cgj_company_id[0],material:JSON.parse(params.material[0]).a,material_id:JSON.parse(params.material[0]).b},
 //        customer:{name:params.contact,tel:params.phone,province:params.province[0],city:params.province[1],area:params.province[2],street:params.address,}
 //      }
 //    }).then((data) => {
 //      if(data.status=='success'){
 //          Toast.success(
 //          '保存成功',
 //          1,
 //          ()=>{
 //            window.location.hash='/hfive/orders';
 //          }
 //        )
        
 //      }else{
 //        Toast.fail(
 //          data.msg,
 //          1
 //        )
 //      }
 //    }).fail( (err, msg) =>{
 //       Toast.offline('网络连接失败!!!', 1);
 //    });
	// }
	handleSubmit(e){
		e.preventDefault();
    let _this=this;
    let _data = null;
    let _saler_id =null;
    // this.props.form.getFieldError('cha_name')
    this.props.form.validateFields((err, values) => {
        // console.log(this.state.payMethods.match(/\d+/g));
        // let chaname= values.chaname!==undefined?values.chaname.match(/\d+/g):null;
        // console.log(JSON.parse(values.material[0]));
        console.log(values)
      if (!err  ) {
        // _this.state.saler_boss!=null;
        console.log('Received values of form: ', values);
      	// _this.loadServer(values)
        _this.state.saler_boss==undefined?_data={name:values.contact,mobile:values.phone.replace(/\s+/g, ""),role:_this.state.radio}:_data={name:values.contact,mobile:values.phone.replace(/\s+/g, ""),role:_this.state.radio,saler_director_id:_this.state.saler_boss};

        reqwest_post('/api/users',{access_token:localStorage['token'],
          user:_data},
          (data)=>{
            if(data.status=='success'){
              Toast.success('保存成功',0.4,()=>{
                window.location.hash='/hfive/users'
              })
            }else{
              Toast.fail(data.msg,0.6)
            }
          }
        )
      }
    });
	}
	componentWillMount(){
    let _this = this;
    let _regions = [];
    // reqwest({
    //   url: window.host+'/api/accounts/get_saler_directors',
    //   method: 'get',
    //   crossOrigin: true,
    //   type: 'json',
    //   data:{access_token:window.localStorage["token"]},
    //   // contentType: 'application/json',
    //   // headers:{
    //   //   'Access-Control-Allow-Origin':'*'
    //   // }
    // }).then((data) => {
    //   if(data.status=='success'){
    //     this.setState({
    //       saler:data.list
    //     })
    //   } 
    // }).fail((err,msg)=>{
    //   console.log(err)
    // });
    reqwest_get('/api/accounts/get_saler_directors',{access_token:window.localStorage["token"]},(data)=>{
      if(data.status=='success'){
        _this.setState({
          saler:data.list
        })
        for(let i of data.list){
          _regions.push({
            value:i['id'],
            label:i['name']
          })
        }
        _this.setState({_regions:_regions})
      }else{
        Toast.fail(data.msg,0.6)
      }
    })
    // console.log(_list)
    // this.setState({saler:_list.list});

	}
  onChange(value,i){
    // console.log(i);
    // let _regions = [];
    // console.log(this.state.saler)
    let _this = this;
    // console.log(this.state.saler_boss)
    this.setState({radio:i.value})
    if(i.value=='saler'){
      this.setState({visible:true}) 
    }
  }
  handleAlert(i){
    // this.setState({})
    this.setState({saler_boss:i.value})
  }
	render(){
		// console.log(this.state.list);
    const {value,value2} =this.state;
		// const { getFieldProps,getFieldsError,getFieldsValue , getFieldError} = this.props.form;
		const _this =this;
    const _companies =[];
    const _material=[];
    let _ag=null;
    let naver=false;
    let saler_dir=null;
    // console.log(this.state.saler)
    // const _slaer = this.state.saler.map(function(data){
    //   console.log(data)
    // })
    const data = [
      { value: 'saler_director', label: '销售主管' },
      { value: 'saler', label: '销售' },
      { value: 'cs', label: '客服' },
      { value: 'acct', label: '财务' },
    ];
    _ag= this.state._regions;
    // console.log(getFieldsError('phone'))
    // console.log(getFieldsError())
    // if(!getFieldsError()){
    //   naver = false;
    // }
    // console.log(this.state._re÷gions)
    // if(validateFields((err,values)))
    const { getFieldProps,getFieldError ,getFieldValue,setFields,getFieldsValue,getFieldsError } = this.props.form;
     let _falg=true;
     let _obj ={}
     // console.log(getFieldsValue())
     if(getFieldValue("phone")){
      // console.log(getFieldsValue()==typeof({}))
      for(let i in getFieldsError()){
        _falg =getFieldError(""+i)!=undefined||getFieldValue(''+i)==undefined?true:false;
        console.log(_falg)
      }
     }
		return(
			<div className={`${style.layout}`}>
				<List className={`${Reset.tel_list_header}`} renderHeader={() => '创建用户'}>
          <InputItem
	          clear
            className={`${Reset.tel_input}`}
	          error={!!getFieldError('phone')}
	          onErrorClick={() => {
	            alert(getFieldError('phone').join('、'));
	          }}
            {...getFieldProps('phone',{
            	rules:[{required:true,message:'请输入手机号码',len:11,validator:(rule,value,callback)=>{
								!!value?numvail(rule,value.replace(/\s+/g, ""),callback):callback('请输入手机号码')
							}}]
            })}
            type='phone'
            placeholder="手机号码"
          >手机号码</InputItem>
          <InputItem
            clear
            placeholder="姓名"
            className={`${Reset.tel_input}`}
            error={!!getFieldError('contact')}
            onErrorClick={() => {
              alert(getFieldError('contact').join('、'));
            }}
            {...getFieldProps('contact',{
              initialValue:undefined,
              rules:[{required:true,message:'姓名'}]
            })}
          >联系人</InputItem>
        </List>
        <List className={`${Reset.tel_list_header}`} renderHeader={() => '选择角色'}>
          <Flex>
            <Flex.Item
              {...getFieldProps('role',{
                rules:[{required:true,message:'选择角色'}]
              })}>
                {data.map((i,index) => (
                  <AgreeItem  key={i.value} data-seed={index} checked={i.value === this.state.radio} className={`${Reset.label} ${Reset.tel_radio}`} onChange={(e) =>{this.onChange(index,i) }}>
                    {i.label}
                  </AgreeItem>
                ))}
            </Flex.Item>
          </Flex>
          
           
        </List>
        {this.state._regions.length<1?null:(<Modal visible={this.state.visible} footer={[
          { text: '取消', onPress: () => this.setState({visible:false}), style: 'default' },
          { text: '选择', onPress: () => this.setState({visible:false}), style: { fontWeight: 'bold' } },
        ]}
        maskClosable={true} transparent={true} 
        title={<span className={`${Reset.tel_modal_title}`}>你可以选择你的销售主管</span>} onClose={()=>{this.setState({visible:false})}} >
          <Flex>
            <Flex.Item>
              {_ag.map((i,index)=>{
                return <AgreeItem  key={i.value} data-seed={'a'+index} checked={i.value === this.state.saler_boss} className={`${Reset.label} ${Reset.tel_radio}`} onChange={(e) =>{this.handleAlert(i)}}>
                  {i.label}
                </AgreeItem>
              })}
            </Flex.Item>
          </Flex>
        </Modal>)}
        <Button disabled={_falg}  className={`${Reset.btn_moblie} ${Reset.tel_btn}`} onClick={this.handleSubmit.bind(this)}  type='primary'>保存</Button>
        <WhiteSpace size="sm" />
			</div>
	 	)
		
	}
}

const OrderForm = createForm()(OrderEdit);
export default connect()(OrderForm)